package qst.com.bacK.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qst.com.bacK.exception.ExamException;
import qst.com.bacK.mapper.UserMapper;
import qst.com.bacK.pojo.entity.User;
import qst.com.bacK.service.UserAdminService;

import java.sql.SQLException;
import java.util.List;

/**
 * Author:   msh
 * Date:     2024/10/11 上午10:35
 * Description:
 */

@Service
public class UserAdminServiceImpl implements UserAdminService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findUsers() {
        return userMapper.findAllUsersType();
    }

    @Override
    public void saveUser(User user) {
        User temp = userMapper.findUserByLoginCount(user.getLogin());
        if (temp != null) {
            throw new ExamException("登录名已经存在了");
        }
        userMapper.insert(user);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public void deleteUserById(int id) {
        User user = userMapper.findById(id);
        if (user == null) {
            return;
        }
        if (user.getLastLogin() != null) {
            throw new ExamException("该用户不能被删除");
        }
        userMapper.delete(id);
    }

    @Override
    public void updateUser(User user) {
        User temp = userMapper.findUserByLoginCount(user.getLogin());
        if (temp != null && temp.getId() != user.getId()) {
            throw new ExamException("登录名已经存在了");
        }
        try {
            userMapper.update(user);
        } catch (SQLException e) {
            throw new ExamException("更新用户信息失败", e);
        }
    }

    @Override
    public void resetPassword(int id) {
        userMapper.updatePassword(id, User.PASSWORD);
    }
}
